package com.yourcompany.service.listener;

import com.yourcompany.api.entity.LoginLog;
import com.yourcompany.api.event.LoginEvent;
import com.yourcompany.api.service.LoginLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 登录事件监听器
 * 用于记录登录日志
 */
@Slf4j
@Component
public class LoginEventListener {
    
    @Autowired
    private LoginLogService loginLogService;
    
    @Async
    @EventListener
    public void handleLoginEvent(LoginEvent event) {
        try {
            LoginLog loginLog = LoginLog.builder()
                .username(event.getUsername())
                .userId(event.getUserId())
                .loginType(event.getLoginType())
                .deviceId(event.getDeviceId())
                .userAgent(event.getUserAgent())
                .status(event.getStatus())
                .msg(event.getMsg())
                .build();
                
            loginLogService.recordLoginLog(loginLog);
        } catch (Exception e) {
            log.error("记录登录日志失败", e);
        }
    }
} 